package leetcode

import kotlinetc.println

/**
Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
 */
fun main(args: Array<String>) {

    println('1'.toInt())
    println('0'.toInt())

    //1010
    //1111
    //    10001
    addBinary("1", "11").println()
}

fun addBinary(a: String, b: String): String {

    val p = if (a.length > b.length) a else b
    val s = if (a.length > b.length) b else a

    var i = p.length - 1

    var j = s.length - 1

    val result = StringBuffer(p.length)

    var carry = 0

    while (i >= 0 || j >= 0) {
        var ii = 0
        var jj = 0

        if (i >= 0 && p[i] == '1') {
            ii++
        }

        if (j >= 0 && s[j] == '1') {
            jj++
        }

        val c = ii + jj + carry

        val curr = c % 2

        carry = (c - curr) / 2

        result.insert(0, (curr + 48).toChar())

        i--
        j--
    }

    if (carry!=0)
        result.insert(0, '1')

    return result.toString()
}